#include "kddcup_feat.h"
#include <vector>
#include <algorithm>

using namespace std;

static const int num_items = 6095;
static const int num_users = 2320895;

int main( int argc, char* argv[] ) {
	if ( argc < 4 ) {
		printf("Usage: train.group output cnt [filter]\n");
		return -1;
	}
    int cnt = atoi( argv[3] );
    int uid, tstamp, uuid;
    FILE *fp = NULL;
    FILE *fi = fopen_check( argv[1], "r" );
    FILE *fo = fopen_check( argv[2], "w" );
    if( argc > 4 ){
        fp = fopen_check( argv[4], "r" );
    }
    
    fprintf( fo, "%d\n", cnt );
    assert_true( fscanf( fi, "%d%*d%*d%d", &uid, &tstamp ) == 2, "BUG" );
    uuid = uid;

    while( uuid != -1 ){
        vector< int > dtstamp, dts;
        while( uuid == uid ){
            dtstamp.push_back( tstamp );
            if( fp != NULL ){
                int pass;
                assert_true( fscanf( fp, "%d", &pass ) == 1, "BUG" );
                if( pass != 0 ){
                    dts.push_back( tstamp ); 
                }
            }else{
                dts.push_back( tstamp );
            }
            if( fscanf( fi, "%d%*d%*d%d", &uid, &tstamp ) != 2 ){
                uid = -1;
            }
        }
        uuid = uid;
        // make data
        sort( dts.begin(), dts.end() );
        // output previous gap and next gap
        for( size_t i = 0; i < dtstamp.size(); i ++ ){
            std::vector<int> tnext;
            int ts = dtstamp[i];
            for( int j = 0; j < cnt; j ++ ){  
                size_t next = std::lower_bound( dts.begin(), dts.end(), ts + 1 ) - dts.begin();
                if( next == dts.size() ) break;
                ts = dts[ next ];
                tnext.push_back( ts );               
            }
            fprintf( fo, "%d", (int) tnext.size() );
            for( size_t j = 0; j < tnext.size(); j ++ ){
                fprintf( fo, " %d:%d", (int)j, tnext[j] - dtstamp[i] );
            }
            fprintf( fo, "\n" );
        }
    }
    fclose( fi ); fclose( fo ); 
    if( fp != NULL ) fclose( fp );
	return 0;
}
